package com.ht.ui.report;

import com.ht.aems.fesmodel.PointManager;
import com.ht.aems.fesmodel.data.AnalogPoint;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JRViewer;

import javax.swing.*;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2010-8-13
 */
public class SimpleAnalogJrMaker extends AbstractAnalogJRMaker {
    private boolean hasNext = true;

    private Map<String, Integer> name2Id;

    public SimpleAnalogJrMaker(URL resource, int mode) {
        super(resource, mode);
    }

    public boolean next() throws JRException {
        hasNext = !hasNext;
        return !hasNext;
    }

    public Object getFieldValue(JRField f) {
        String fieldName = f.getName();
        try {
            if (name2Id.containsKey(fieldName))
                return nId2Values.get(name2Id.get(fieldName));
            else
                return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setName2Id(Map<String, Integer> name2Id) {
        this.name2Id = name2Id;
    }

    public JPanel createViewer(long start, long end) {
        JasperReport jasperReport;
        HashMap<String, Object> pMap = new HashMap<String, Object>();
        pMap.put("date", new Date(start));
        try {
            jasperReport = (JasperReport) JRLoader.loadObject(resource);
        } catch (JRException e) {
            e.printStackTrace();
            return null;
        }
        JasperPrint jasperPrint;
        try {
            JRField[] fields = jasperReport.getFields();
            int[] nids = new int[fields.length];
            Map<String, Integer> name2id = new HashMap<String, Integer>(fields.length);
            int index = 0;
            for (JRField f : fields) {
                AnalogPoint p = PointManager.getInstance().getAnalogPoint(f.getName());
                if (p != null) {
                    nids[index++] = p.getId();
                    name2id.put(f.getName(), p.getId());
                } else
                    nids[index++] = -1;
            }
            setName2Id(name2id);
            loadValueFormDB(nids, new Date(start));
            jasperPrint = JasperFillManager.fillReport(jasperReport, pMap, this);
        } catch (JRException e) {
            e.printStackTrace();
            return null;
        }
        JRViewer viewer = new JRViewer(jasperPrint);
        viewer.setFitPageZoomRatio();
        prints.put(viewer, jasperPrint);
        return viewer;
    }
}
